package com.unknowpupil.web.service.impl;

import com.unknowpupil.web.base.Result;
import com.unknowpupil.web.base.impl.BaseCrudServiceImpl;
import com.unknowpupil.web.component.wallet.entity.CoinWallet;
import com.unknowpupil.web.domain.Account;
import com.unknowpupil.web.domain.AccountInfo;
import com.unknowpupil.web.exception.MxException;
import com.unknowpupil.web.tool.ConstantsTool;
import com.unknowpupil.web.tool.CreateInvitationWordTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.unknowpupil.web.mapper.AccountInfoMapper;
import com.unknowpupil.web.service.IAccountInfoService;
import tk.mybatis.mapper.entity.Example;

/**
 * @Classname: AccountInfoServiceImpl
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2019/11/6 14:21
 * @Description:
 * @Version: 1.0
 */
@Service
public class AccountInfoServiceImpl extends BaseCrudServiceImpl<AccountInfo, AccountInfoMapper> implements IAccountInfoService {

    @Resource
    private AccountInfoMapper accountInfoMapper;

    @Override
    public AccountInfo createAccountInfo(String password, Account account, CoinWallet ethWallet) throws MxException {
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setUserName(account.getUserName());
        accountInfo.setEthAddress(ethWallet.getAddress());
        accountInfo.setEthPublicKey(ethWallet.getPublicKey());
        accountInfo.setEthPrivateKey(ethWallet.getPrivateKey());
        accountInfo.setMnemonicCode(ethWallet.getMnemonicCode());
        accountInfo.setUserId(account.getId());
        accountInfo.setFileName(ethWallet.getFileName());
        accountInfo.setStatus(0);
        accountInfo.setDelFlag(0);
        return save(accountInfo);
    }

    @Override
    public Result getAccountInfo(String userId) {
        Example example = new Example(AccountInfo.class);
        example.createCriteria().andEqualTo("userId", userId);
        AccountInfo accountInfo = accountInfoMapper.selectOneByExample(example);
        accountInfo.setFileName(null);
        accountInfo.setMnemonicCode(null);
        //todo:私钥在传递过程中需要加密，前端解密，相应的前端往后台传也需要加密
        accountInfo.setEthPrivateKey(accountInfo.getEthPrivateKey());
        return Result.ok(accountInfo);
    }

    @Override
    public int findAddressByTo(String to) {
        Example example = new Example(AccountInfo.class);
        example.createCriteria().andEqualTo("ethAddress", to);
        return accountInfoMapper.selectCountByExample(example);
    }

    @Override
    public String findUserNameByAddress(String address) {
        return accountInfoMapper.findUserNameByAddress(address);
    }
}
